
package com.joysuch.wwyt.quartz.bp;

import java.util.List;

import javax.transaction.Transactional;

import com.joysuch.wwyt.bp.entity.BpWorkSafetyCert;
import com.joysuch.wwyt.bp.repository.BpWorkSafetyCertDao;
import com.joysuch.wwyt.core.quartz.ResetTimeSequenceBizCodesSeedJob;
import com.joysuch.wwyt.risk.repository.RiskPointDao;
import com.joysuch.wwyt.risk.service.RiskDistrictService;
import com.joysuch.wwyt.risk.service.RiskEvaluationRepoService;
import com.joysuch.wwyt.risk.service.RiskPointService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * 定时任务实现如下功能:
 * <ul>
 * <li>1. 加载已验收，但是作业结束状态为否的所有作业任务</li>
 * <li>2. 检查任务是否关联了作业评估，如果关联了评估，则更新风险点、风险分区的评估级别</li>
 * <li>3. 将作业证状态改为已结束</li>
 * </ul>
 *
 * @author zhangxiaohuan
 * @company huanke
 * @date 2019年12月15日 下午12:35:52
 * @since
 *
 */
@Service
public class CheckWorkSafetyCertJob {

    private static final Logger logger = LoggerFactory.getLogger(ResetTimeSequenceBizCodesSeedJob.class);

    @Autowired
    private BpWorkSafetyCertDao workSafetyCertDao;
    @Autowired
    private RiskPointDao riskPointDao;
    @Autowired
    private RiskPointService riskPointService;
    @Autowired
    private RiskDistrictService riskDistrictService;
    @Autowired
    private RiskEvaluationRepoService riskEvaluationRepoService;

    @Transactional
    @Scheduled(cron = "0 0 1 * * ?")
    public void check() {
        try {
            logger.info("开始处理作业证");
            // quatz使用的是独立的线程，不会包含有Context中相关信息，所以不会被拦截，添加tenentId,orgCode字段。查询出的是所有租户的数据
            List<BpWorkSafetyCert> unFinisedJobs = workSafetyCertDao.findUnProcessedJob();
            logger.info("待处理的已经完成的作业证个数:" + unFinisedJobs.size());
            for (BpWorkSafetyCert cert : unFinisedJobs) {
                try {
                    // try catch 防止当个任务失败影响其他业务
                    processCert(cert);
                } catch (Exception e) {
                    logger.error("处理作业证出错#" + cert.getId(), e);
                }
            }
            logger.info("作业证处理完成");
        } catch (Exception e) {
            logger.error("作业证处理出错", e);
        }
    }

    private void processCert(BpWorkSafetyCert cert) {
        if (cert.getJhaEvaluationId() != null && cert.getRiskPointId() != null) {
            riskEvaluationRepoService.evaluationOutOfDate(cert.getJhaEvaluationId());
        }
        cert.setJobFinished(1);
        workSafetyCertDao.save(cert);
    }

}
